package cn.zyq.demo.service.sys.impl;


import cn.zyq.demo.beans.sys.SysAdmin;
import cn.zyq.demo.beans.sys.SysDept;
import cn.zyq.demo.beans.sys.SysRole;
import cn.zyq.demo.mapper.sys.SysDeptMapper;
import cn.zyq.demo.mapper.sys.SysRoleMapper;
import cn.zyq.demo.service.sys.SysDeptService;
import cn.zyq.demo.system.common.BaseService;
import cn.zyq.demo.system.common.PageParam;
import cn.zyq.demo.system.ry.UserConstants;
import cn.zyq.demo.system.ry.model.TreeSelect;
import cn.zyq.demo.system.ry.util.SecurityUtils;
import cn.zyq.demo.system.ry.util.SpringUtils;
import cn.zyq.demo.system.ry.util.StringUtils;
import cn.zyq.demo.system.utils.text.Convert;
import com.aliyun.oss.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门表
 * 2023-05-12 20:14:08
 */

@Slf4j
@Service
public class SysDeptServiceImpl extends BaseService implements SysDeptService {
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Override
    public List<SysDept> list(PageParam pageParam, SysAdmin admin) {
        // PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        List<SysDept> dbList = this.sysDeptMapper.list(pageParam.getKv());
        return dbList;
    }

    @Override
    public void add(SysDept param, SysAdmin admin) {
        SysDept info = sysDeptMapper.selectByPrimaryKey(param.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new ServiceException("部门停用，不允许新增");
        }
        param.setAncestors(info.getAncestors() + "," + param.getParentId());
        this.setCreateBaseData(param, admin);
        this.sysDeptMapper.insertSelective(param);
    }

    @Override
    public void update(SysDept dept, SysAdmin admin) {
        Integer id = dept.getSysDeptID();
        SysDept newParentDept = sysDeptMapper.selectByPrimaryKey(dept.getParentId());
        SysDept oldDept = sysDeptMapper.selectByPrimaryKey(dept.getSysDeptID());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getSysDeptID();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getSysDeptID(), newAncestors, oldAncestors);
        }
        int result = this.sysDeptMapper.updateByPrimaryKeySelective(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        this.setUpdateBaseData(dept, admin);
        this.sysDeptMapper.updateByPrimaryKeySelective(dept);
    }

    @Override
    public void del(String serviceID, SysAdmin admin) {
        SysDept dbInfo = this.detail(serviceID);
        Integer id = dbInfo.getSysDeptID();
        this.deleteLogic(id, admin, this.sysDeptMapper);
    }

    @Override
    public SysDept detail(String serviceID, SysAdmin admin) {
        return this.detail(serviceID);
    }

    @Override
    public SysDept detail(String serviceID) {
        SysDept dbInfo = this.getByServiceID(serviceID, SysDept.class, this.sysDeptMapper);
        this.checkLogicExist(dbInfo);
        return dbInfo;
    }

    /**
     * 校验部门是否有数据权限
     *
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(Integer deptId) {
        if (!SysAdmin.isAdmin(SecurityUtils.getSysAdminID())) {
            SysDept dept = new SysDept();
            dept.setSysDeptID(deptId);
            List<SysDept> depts = SpringUtils.getAopProxy(this).sysDeptMapper.select(dept);
            if (StringUtils.isEmpty(depts)) {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    @Override
    public SysDept selectDeptById(Integer deptId) {
        return sysDeptMapper.selectDeptById(deptId);
    }


    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameUnique(SysDept dept) {
        int deptId = StringUtils.isNull(dept.getSysDeptID()) ? -1 : dept.getSysDeptID();
        SysDept info = sysDeptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getSysDeptID() != deptId) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int selectNormalChildrenDeptById(Integer deptId) {
        return sysDeptMapper.selectNormalChildrenDeptById(deptId);
    }

    @Override
    public boolean hasChildByDeptId(Integer deptId) {
        int result = sysDeptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    @Override
    public boolean checkDeptExistUser(Integer deptId) {
        int result = sysDeptMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Integer deptId) {
        return sysDeptMapper.deleteByPrimaryKey(deptId);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Integer deptId, String newAncestors, String oldAncestors)
    {
        List<SysDept> children = sysDeptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            sysDeptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept)
    {
        String ancestors = dept.getAncestors();
        Integer[] deptIds = Convert.toIntArray(ancestors);
        sysDeptMapper.updateDeptStatusNormal(deptIds);
    }


    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Integer> selectDeptListByRoleId(Integer roleId)
    {
        SysRole role = roleMapper.selectRoleById(roleId);
        return sysDeptMapper.selectDeptListByRoleId(roleId, role.getDeptCheckStrictly());
    }
    /**
     * 查询部门树结构信息
     *
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<TreeSelect> selectDeptTreeList(SysDept dept)
    {
        // List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
        List<SysDept> depts = this.selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }
    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    public List<SysDept> selectDeptList(SysDept dept)
    {
        return sysDeptMapper.selectDeptList(dept);
    }
    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts)
    {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }
    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts)
    {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Integer> tempList = depts.stream().map(SysDept::getSysDeptID).collect(Collectors.toList());
        for (SysDept dept : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t)
    {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t)
    {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext())
        {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getSysDeptID().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t)
    {
        return getChildList(list, t).size() > 0;
    }
}
